import { ref, h, onMounted } from "vue";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { useRoute } from "vue-router";
import { useRouterNavigation } from "@/router/utils";
import { dayjs, type TabsPaneContext } from "element-plus";
import editForm from "../../form/index.vue";
import type { FormItemProps } from "../../utils/types";
import { addDialog } from "@/components/ReDialog";
import { message } from "@/utils/message";
import { cloneDeep } from "@pureadmin/utils";
import { dealDataRide, dealDataExcept } from "@/utils/common";
import {
  getStoreDetail,
  storeUpdate
} from "@/api/basicArchives/storeManagement";

export function useStoreDetil() {
  // 返回上一页
  const { go } = useRouterNavigation();
  function goBack(n) {
    go(n);
  }

  const activeName = ref();
  const handleClick = (tab: TabsPaneContext) => {
    console.log(tab);
  };

  const columns: TableColumnList = [
    {
      label: "业务日期",
      prop: "bizDate"
    },
    {
      label: "抓机商品",
      prop: "captureGoodsPrice",
      formatter: ({ captureGoodsPrice }) =>
        dealDataExcept(captureGoodsPrice) || 0
    },
    {
      label: "兑换礼品",
      prop: "exchangeGiftPrice",
      formatter: ({ exchangeGiftPrice }) =>
        dealDataExcept(exchangeGiftPrice) || 0
    },
    {
      label: "创建人",
      prop: "createUserName"
    },
    {
      label: "创建时间",
      prop: "gmtCreate",
      formatter: ({ gmtCreate }) => dayjs(gmtCreate).format("YYYY-MM-DD HH:mm")
    }
  ];

  const tableData = [
    {
      name: "Tom",
      address: "No. 189, Grove St, Los Angeles"
    },
    {
      name: "Jack",
      address: "No. 189, Grove St, Los Angeles"
    },
    {
      name: "Tom",
      address: "No. 189, Grove St, Los Angeles"
    },
    {
      name: "Jack",
      address: "No. 189, Grove St, Los Angeles"
    }
  ];

  const formRef = ref();

  function openDialog(title = "新增", row?: FormItemProps) {
    addDialog({
      title: `${title}门店`,
      props: {
        formInline: {
          id: row?.id ?? "",
          storeName: row?.storeName ?? "",
          wtCode: row?.wtCode ?? undefined,
          contacts: row?.contacts ?? "",
          address: row?.address ?? "",
          contact: row?.contact ?? "",
          type: row?.type ?? "",
          brandId: row?.brandId ?? "",
          areaId: row?.areaId ?? "",
          labelIdList: row?.labelIdList ?? [],
          depositoryIdList: row?.depositoryIdList ?? [],
          avgPrice: dealDataExcept(row?.avgPrice) ?? "",
          des: row?.des ?? ""
        }
      },
      width: "30%",
      fullscreenIcon: true,
      closeOnClickModal: false,
      sureBtnLoading: true,
      contentRenderer: () => h(editForm, { ref: formRef }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = cloneDeep(options.props.formInline as FormItemProps);

        // 小娃娃均价放大10倍
        curData.avgPrice = dealDataRide(curData.avgPrice);
        function chores() {
          message(`操作成功`, {
            type: "success"
          });
          getDetailInfo();
          setTimeout(() => done(), 800); // 关闭弹窗
        }
        FormRef.validate(async valid => {
          if (valid) {
            // console.log("curData", curData);
            // 表单规则校验通过
            if (title === "新增") {
              // 实际开发先调用新增接口，再进行下面操作
              chores();
            } else {
              // 实际开发先调用修改接口，再进行下面操作
              const { code } = await storeUpdate(curData);
              if (code == 200) {
                chores();
              }
            }
          }
        });
      }
    });
  }

  const storeId = ref<any>("");
  const storeInfo = ref<any>({});

  async function getDetailInfo() {
    const res = await getStoreDetail({ id: storeId.value });
    storeInfo.value = res.data;
    if (res.data.depositoryList.length > 0) {
      activeName.value = res.data.depositoryList[0].depositoryName;
    }
  }

  onMounted(async () => {
    const { query } = useRoute();
    storeId.value = query.id;
    if (query.id) getDetailInfo();
  });

  return {
    activeName,
    columns,
    tableData,
    storeInfo,
    useRenderIcon,
    goBack,
    handleClick,
    openDialog
  };
}
